# apps/tenants/middleware.py
from django.utils.deprecation import MiddlewareMixin
from django.urls import resolve
from .models import Tenant

class TenantMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 从请求头或子域名获取租户码
        tenant_code = request.META.get('HTTP_X_TENANT_CODE') or request.GET.get('tenant')
        if tenant_code:
            try:
                tenant = Tenant.objects.get(code=tenant_code, is_active=True)
                request.tenant = tenant
            except Tenant.DoesNotExist:
                request.tenant = None
        else:
            request.tenant = None